package org.spring.test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.test.dto.RolDto;
import org.hibernate.test.dto.UserDto;
import org.hibernate.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class CustomUserDetailsService implements UserDetailsService {
	protected static Logger logger = Logger.getLogger("service");

	@Autowired
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		CustomUserDetails user = null;
		UserDto userdb = userService.findUserByNickName(username);
		if (userdb != null) {
			user = new CustomUserDetails(userdb.getNick(), userdb.getPassword(), true, true, true, true, getAuthorities(userdb.getRol()));
			user.setLastName(userdb.getLastName());
			user.setIdUser(userdb.getId());
			user.setFirtsName(user.getFirtsName());
			
		} else {
			throw new UsernameNotFoundException("No se encontro informacion del usuario en la base de datos");
		}

		return user;
	}

	public Collection<GrantedAuthority> getAuthorities(RolDto rol) {
		// Create a list of grants for this user
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		logger.debug("Grant " + rol.getName() + " to this UserDto");
		authList.add(new SimpleGrantedAuthority(rol.getName()));
		return authList;
	}

}
